<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\MoneyLog;
use app\common\model\order\Order;
use app\common\model\ScoreLog;
use app\common\model\user\Level;
use app\common\model\user\Log;
use PDOException;
use think\Db;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->assignconfig("levelList", $this->model->getLevelList());
        $this->assignconfig("groupList", $this->model->getGroupList());
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['puser'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                $team_ids = $this->model->where("find_in_set({$v->id},paren_ids)")->column('id');
                $ids = $this->model->where('pid', $v->id)->column('id');
                $v->team = count($team_ids);
                $v->push = count($ids);
                $v->push_performance = Order::whereIn('user_id', $ids)->whereIn('status', ['1', '2', '3', '4'])->sum('pay_money-freight');
                // $v->total_dividend = Order::where('user_id', $v->id)->whereIn('status', ['1','2','3','4'])->sum('dividend');
                $v->y_dividend = bcsub($v->total_dividend, $v->use_dividend, 2) > 0 ? bcsub($v->total_dividend, $v->use_dividend, 2) : 0;

                $v->team_performance = Order::whereIn('user_id', $team_ids)->whereIn('status', ['1', '2', '3', '4'])->sum('pay_money-freight');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $freight = Order::whereTime('paytime', 'years')->whereIn('status', ['1', '2', '3', '4'])->sum('freight');
        $payMoney = Order::whereTime('paytime', 'years')->whereIn('status', ['1', '2', '3', '4'])->sum('pay_money');
        $count = MoneyLog::whereTime('createtime', 'between', [date('Y-12-31'), date('Y-12-31 23:59:59')])->count();
        $this->view->assign('count', $count);
        $this->view->assign('money', bcsub($payMoney, $freight ?? 0, 2));
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }
    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('level,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $text = json_encode([
                'group_id' => $row->group_id,
                'total_interests' => $row->total_interests,
                'total_dividend' => $row->total_dividend,
                'use_dividend' => $row->use_dividend,
            ]);
            $result = $row->allowField(true)->save($params);
            if ($result) {

                $log = new Log;
                $data = [
                    'user_id' => $params['id'],
                    'admin_id' => $this->auth->id,
                    'content' => $params['content'],
                    'json' => json_encode([
                        'group_id' => $params['group_id'],
                        'total_interests' => $params['total_interests'],
                        'total_dividend' =>  $params['total_dividend'],
                        'use_dividend' =>  $params['use_dividend'],
                    ]),
                    'text' => $text,
                ];
                $log->allowField(true)->save($data);
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
    /**
     * 扫码权限
     */
    public function scan($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $scan = $row->scan == 1 ? 0 : 1;
        $row->save(['scan' => $scan]);
        $this->success();
    }

    /**
     * 余额编辑
     *
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function yue($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($params['money'] > $row->money && $params['type'] == 1) {
            $this->error(__('余额不足', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['money'] > 0) {
                $result = MoneyLog::income($row->id, $params['money'], $params['type'], 600, '', 0, $params['memo']);
            }
            if ($params['score'] > 0) {
                $result = ScoreLog::income($row->id, $params['score'], $params['type'], 100, '',  $params['memo']);
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 董事分红
     *
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function dividend($ids = null)
    {
        try {
            MoneyLog::dividend();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();
    }
}
